var countdown=require('../public/javascripts/countdown'),sdc = require('sdc-clients')

var dc_config=require('../config/dc')['poc']
	,ufds = new sdc.UFDS(dc_config.ufds)

	function findUser(user,cb){
		return ufds.getUser(user, function (err, user) {
			if (err) {
				if (err.restCode === 'ResourceNotFound')return cb({path:'loginView.html',message:'用户名不存在'})
				return cb({path:'loginView.html',message:'系统异常，请稍后重试'})
			}
			var locked = user.pwdaccountlockedtime && (new Date()).getTime() < user.pwdaccountlockedtime;
			if (locked)return cb({path:'loginView.html',message:'账号已被锁定'})
			user.path='userZone.html'
			return cb(user)
		})
	}
module.exports = {
	addUser:function(req, res) {
		ufds.addUser(req.params.account, function (err, user) {
			console.log(err||user)
		})
	},
	addKey:function(req, res) {
		ufds.addKey(req.headers.userid,{openssh: req.body.key},req.params.account, function (err, key) {
			console.log(err||key)
		})
	},
	loginView:function(req, res) {
		if(req.headers.userid&&req.headers.userid!='null')
			return findUser(req.headers.userid,function(data){
				res.send(data)
			})
		return res.send({path:'loginView.html'})
	},
	loginAction:function(req, res) {
		var start=new Date()
		ufds.authenticate(req.params.login,req.params.password,function(er, user){
		var end=new Date()
			if(user){
				user.sdc7time=countdown(start,end).toString()
				user.path='userZone.html'
				return res.send(user)
			}
			if(er.statusCode===404)return res.send({message:'账号不存在!'})
			if(er.statusCode===401)return res.send({message:'用户名或密码错误!'})
		})
	}
}